package com.huawei.hwmdemo.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.annotation.DrawableRes;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.widget.Toast;



import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.huawei.cloudlink.openapi.HWMSdk;
import com.huawei.hwmconf.presentation.util.DateUtil;
import com.huawei.hwmconf.sdk.model.conf.entity.AttendeeModel;
import com.huawei.hwmconf.sdk.model.conf.entity.ConfBaseInfo;
import com.huawei.hwmconf.sdk.model.conf.entity.ConfInfo;
import com.huawei.hwmconf.sdk.util.BaseDateUtil;
import com.huawei.hwmconf.sdk.util.Utils;
import com.huawei.hwmdemo.R;
import com.huawei.hwmdemo.model.ApiPageModel;
import com.huawei.hwmdemo.model.ConfItemModel;
import com.huawei.hwmfoundation.HwmContext;
import com.huawei.hwmfoundation.utils.PreferenceUtils;
import com.huawei.hwmlogger.HCLog;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;

public class DemoUtil {
    private static final String TAG = DemoUtil.class.getSimpleName();

    private static DemoUtil mInstance = null;

    public synchronized static DemoUtil getInstance() {
        if (mInstance == null) {
            mInstance = new DemoUtil();
        }
        return mInstance;
    }

    public static List<AttendeeModel> attendeeModels;

    public static List<AttendeeModel> selectModels;

    public static ConfInfo customizeQR;

    public static void clearSelectModels() {
        if (selectModels != null) {
            selectModels.clear();
        }
    }

    public static boolean needCustom(String customStr) {
        return PreferenceUtils.read(PreferenceUtils.PREFERENCES_NAME, customStr, false, Utils.getApp());
    }

    public static void setCustom(String customStr, ApiPageModel model) {
        PreferenceUtils.save(PreferenceUtils.PREFERENCES_NAME, customStr, !model.checkStyle, Utils.getApp());
    }

    private static boolean packageInstalled(Context context, String packageName) {
        PackageInfo packageInfo = null;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
        return packageInfo != null;
    }

    public static void openCloudLinkWithURL(Context context, String url) {
        if (DemoUtil.packageInstalled(context, "com.huawei.CloudLink")) {
            Intent intent = new Intent();
            intent.setData(Uri.parse(url));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } else {
            showToast("应用未安装");
        }

    }

    public static void showToast(String msg) {
        HwmContext.getInstance()
            .runOnMainThread(() -> Toast.makeText(HWMSdk.getApplicationContext(), msg, Toast.LENGTH_LONG).show());
    }

    public static RecyclerView.ItemDecoration getRecyclerViewDivider(Context context, @DrawableRes int drawableId) {
        DividerItemDecoration itemDecoration = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL);
        itemDecoration.setDrawable(context.getResources().getDrawable(drawableId));
        return itemDecoration;
    }

    public static boolean isApkInDebug(Context context) {
        try {
            ApplicationInfo info = context.getApplicationInfo();
            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (Exception e) {
            return false;
        }
    }

    private ConfItemModel transform(ConfBaseInfo ckConfListInfo) {
        ConfItemModel confItemModel = new ConfItemModel();
        String startTime = DateUtil.getLocalTimeString(ckConfListInfo.getStartTime());
        confItemModel.setStartTime(startTime);
        String endTime = DateUtil.getLocalTimeString(ckConfListInfo.getEndTime());
        confItemModel.setEndTime(endTime);
        confItemModel.setConfId(ckConfListInfo.getConfId());
        confItemModel.setVmrConferenceId(ckConfListInfo.getVmrConferenceId());
        confItemModel.setConfSubject(ckConfListInfo.getConfSubject());
        confItemModel.setMediaType(ckConfListInfo.getMediaType());
        confItemModel.setScheduserName(ckConfListInfo.getScheduserName());
        confItemModel.setAccessNumber(ckConfListInfo.getAccessNumber());
        confItemModel.setChairmanPwd(ckConfListInfo.getChairmanPwd());
        confItemModel.setGeneralPwd(ckConfListInfo.getGuestPwd());
        return confItemModel;
    }

    public List<ConfItemModel> transform(List<ConfBaseInfo> ckConfListInfos) {
        if (ckConfListInfos == null || ckConfListInfos.size() == 0) {
            return null;
        }
        List<ConfBaseInfo> temp = new ArrayList<>(ckConfListInfos);
        Collections.sort(temp, (ckConfListInfo1, ckConfListInfo2) -> {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
            try {
                Date dt1 = format.parse(
                    BaseDateUtil.timeStamp2GMTDate(ckConfListInfo1.getStartTime(), BaseDateUtil.FMT_YMDHM));
                Date dt2 = format.parse(
                    BaseDateUtil.timeStamp2GMTDate(ckConfListInfo2.getStartTime(), BaseDateUtil.FMT_YMDHM));
                if (dt1.getTime() > dt2.getTime()) {
                    return 1;
                } else if (dt1.getTime() < dt2.getTime()) {
                    return -1;
                } else {
                    return 0;
                }
            } catch (Exception e) {
                HCLog.e(TAG, " transform error ");
            }
            return 0;
        });

        ckConfListInfos.clear();
        ckConfListInfos.addAll(temp);

        List<ConfItemModel> confItemModels = new ArrayList<>();
        if (!ckConfListInfos.isEmpty()) {
            for (ConfBaseInfo ckConfListInfo : ckConfListInfos) {
                confItemModels.add(transform(ckConfListInfo));
            }
        }
        return confItemModels;
    }

    //创建二维码Bitmap对象
    public static Bitmap createQRCodeBitmap(String content, int width, int height, String characterSet,
                                            String errorCorrectionLevel, String margin, int colorBlack, int colorWhite) {
        if (TextUtils.isEmpty(content)) {
            return null;
        }
        if (width < 0 || height < 0) {
            return null;
        }
        try {
            Hashtable<EncodeHintType, String> hints = new Hashtable<>();
            if (!TextUtils.isEmpty(characterSet)) {
                hints.put(EncodeHintType.CHARACTER_SET, characterSet);
            }
            if (!TextUtils.isEmpty(errorCorrectionLevel)) {
                hints.put(EncodeHintType.ERROR_CORRECTION, errorCorrectionLevel);
            }
            if (!TextUtils.isEmpty(margin)) {
                hints.put(EncodeHintType.MARGIN, margin);
            }
            BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);

            int[] pixels = new int[width * height];
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * width + x] = colorBlack;
                    } else {
                        pixels[y * width + x] = colorWhite;
                    }
                }
            }
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            return bitmap;
        } catch (WriterException e) {
            return null;
        }
    }

    public static String getErrMsg(Context context, int errCode) {
        return getLoginErrTips(context, errCode);
    }


    private static String getLoginErrTips(Context context, int error) {
        switch (error) {
            case 10001:
                return context.getString(R.string.hwmconf_login_err_general);
            case 10002:
                return context.getString(R.string.hwmconf_login_err_param);
            case 10003:
                return context.getString(R.string.hwmconf_login_err_request_timeout);
            case 10004:
                return context.getString(R.string.hwmconf_login_err_network_err);
            case 10005:
                return context.getString(R.string.hwmconf_login_err_certificate_verify_failed);
            case 10006:
                return context.getString(R.string.hwmconf_login_err_account_pwd_err);
            case 10007:
                return context.getString(R.string.hwmconf_login_err_account_locked);
            case 10008:
                return context.getString(R.string.hwmconf_login_err_ip_or_device_forbidden);
            case 10009:
                return context.getString(R.string.hwmconf_login_err_corp_or_account_inactive);
            case 10010:
                return context.getString(R.string.hwmconf_login_err_server_upgrade);
            case 10011:
                return context.getString(R.string.hwmconf_login_err_fist_login_change_password);
            case 10012:
                return context.getString(R.string.hwmconf_login_err_already_login);
            default:
                break;
        }
        return context.getString(R.string.hwmconf_login_err_general);
    }

}
